<?php
	/**
	 * @author Matthias Eigner | 0625203
	 */
	class DatabaseInterface {

		private $user_tmp;
		
		function __construct(){
			$this->user_tmp = array();
			$GLOBALS['db_connections'] = 0;
			$GLOBALS['waited_time'] = 0;
		}
		
		/**
		 * 
		 * Gets User-data from the Server
		 * @param $id
		 * @param $array | if true an array will be retrned
		 * @param $force_reload | if true a reload from the server will be forced else $user_tmp will be used (just workes for $array=false)
		 */
		public function getUserById($id, $array=false, $force_reload=false){
			if(!$force_reload && !$array && in_array($id, array_keys($this->user_tmp))){
				return $this->user_tmp[$id];
			}
			$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=getUser&uID='.$id.'&sID='.$_SESSION['server_sID']), true);
			if(isset($req['u'])){
				if($array){
					return array('nick'=>$req['u']['nick'],
								'u_id'=>$req['u']['uID'],
								'email'=>$req['u']['email'],
								'group'=>$req['u']['group']);
					break;
				} else {
					$this->user_tmp[$id] = new UserDescription($req['u']['nick'], $req['u']['uID'], $req['u']['fN'], $req['u']['lN'], $req['u']['email']);
					return $this->user_tmp[$id];
					break;
				}
			}
			return array('Error'=>$req['eMsg']);
		}
		
		/**
		 * 
		 * creates a New User
		 * @param string $nick
		 * @param string $fN | first name
		 * @param string $lN | last name
		 * @param strin $email
		 * @param string $pwd
		 */
		public function newUser($nick, $fN, $lN, $email, $pwd){
			$bug = '&name=';
			$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=newUser&sID='.$_SESSION['server_sID'].'&nick='.$nick.'&fN='.$fN.'&lN='.$lN.'&email='.$email.'&pw='.$pwd.$bug), true);
			if(!isset($req['eMsg'])){
				return true;
				break;
			}
			return array('Error'=>$req['eMsg']);
		}
		
		/**
		 * 
		 * Updates a User at the Server
		 * @param int $id
		 * @param string $fN | first Name
		 * @param string $lN | last Name
		 * @param string $email
		 * @param int $status | see UserDescription::const
		 * @param string $opwd | old Password
		 * @param string $npwd | new Password
		 */
		public function editUser($id, $fN, $lN, $email, $opwd='', $npwd=''){
			$pwd = ($opwd != '' && $npwd != '') ? '&oPw='.urlencode($opwd).'&nPw='.urlencode($npwd) : '';
			
			$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=editUser&sID='.$_SESSION['server_sID'].'&uID='.$id.'&fN='.urlencode($fN).'&lN='.urlencode($lN).'&email='.urlencode($email).$pwd), true);
			if(!isset($req['eMsg'])){
				return true;
				break;
			}
			return array('Error'=>$req['eMsg']);
		}
		
		/**
		 * 
		 * Deletes User
		 * @param int $id
		 */
		public function deleteUser($id){
			$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=deleteUser&sID='.$_SESSION['server_sID'].'&uID='.$id), true);
			if(!isset($req['eMsg'])){
				return true;
				break;
			}
			return array('Error'=>$req['eMsg']);
		}
		
		/**
		 * 
		 * Gets all Users to a list/todo/all
		 * @param $lID
		 * @param $tID
		 */
		public function getUsers($lID=-1, $tID=-1, $from=-1, $rows=-1){
			$limit = (($rows == -1) || ($from == -1)) ? '' : '&from='.$from.'&rows='.$rows;
			$lID = ($lID!=-1) ? '&lID='.$lID : '';
			$tID = ($tID!=-1) ? '&tID='.$tID : '';
			$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=getUsers&sID='.$_SESSION['server_sID'].$lID.$tID.$limit), true);
			//echo $GLOBALS['server'].'index.php?action=getUsers&sID='.$_SESSION['server_sID'];
			if(!isset($req['eMsg'])){
				$re = array();
				foreach($req['u'] as $user){
					$re[] = new UserDescription($user['nick'], $user['uID'], $user['fN'], $user['lN'], $user['email']);
				}
				return $re;
			} else return array('Error'=>$req['eMsg']);
		}
	
		/**
		 * 
		 * Returns Number of all Users
		 */
		public function getUserCount(){
			$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=getUsers&sID='.$_SESSION['server_sID'].'&rows=0&from=0'), true);
			if(!isset($req['eMsg'])){
				return $req['uC'];
			} else return array('Error'=>$req['eMsg']);
		}
		
		/**
		 * Logs a User in at the Server
		 * returns True if Login at the Server was successfull
		 * 
		 * @param String $name
		 * @param String $pwd
		 * @return boolean
		 */
		public function login($name, $pwd){
			$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=login&name='.$name.'&pw='.$pwd), true);
			if((isset($req['iE']) && !$req['iE'])){
				$_SESSION['server_sID'] = $req['sID'];
				return $req['uID'];
				break;
			}
			return false;
		}
		
		/**
		 * 
		 * Logout of a User
		 */
		public function logout(){
			$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=logout&sID='.$_SESSION['server_sID']), true);
			if(!isset($req['eMsg'])){
				return true;
				break;
			} else return array('Error'=>$req['eMsg']);
		}
		
		/**
		 * 
		 * Get Todos from server
		 * @param $from | limit
		 * @param $rows
		 * @param $sort | sort (cD, tD, pH, or s)
		 * @param $past | flag to exclude past todos
		 * @return Todo[]
		 */
		public function getTodos($from=-1, $rows=-1, $sort='', $past=true){
			$limit = (($rows == -1) || ($from == -1)) ? '' : '&from='.$from.'&rows='.$rows;
			$past = ($past) ? '': '&iP=false';
			switch($sort){
				case 'cD': //change Date
					$sort = '&sort=cD';
					break;
				case 'tD': // target Date
					$sort = '&sort=tD';
					break;
				case 'pH': // projected Hours
					$sort = '&sort=pH';
					break;
				case 's':
					$sort = '&sort=s';
					break;
				default:
					$sort = '';
					break;
			}
			$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=getTodos&order=asc&sID='.$_SESSION['server_sID'].$limit.$sort.$past), true);
			//print_r($req);
			if(isset($req['todos']) && is_array($req['todos'])){
				$GLOBALS['todos_allcount'] = $req['tC'];
				$td = array();
				foreach($req['todos'] as &$todo){
					$t = new Todo($todo['id'], 
									$todo['title'],
									$todo['text'],
									$todo['tD'],
									$todo['pH'],
									$this->getUserById($todo['creator']),
									$todo['status']);
					$t->setTodoCount($req['tC']);
					$td[] = $t;
				}
				return $td;
			} else return array('Error'=>$req['eMsg']);
			
		}
		
		/**
		 * 
		 * gets Todos for a List
		 * @param int $lId
		 * @param int $from
		 * @param int $rows
		 * @param string $sort
		 * @param boolean $past
		 */
		public function getTodosForList($lId, $from=-1, $rows=-1, $sort='', $past=true) {
			$limit = (($rows == -1) || ($from == -1)) ? '' : '&from='.$from.'&rows='.$rows;
			$past = ($past) ? '': '&iP=false';
			switch($sort){
				case 'cD': //change Date
					$sort = '&sort=cD';
					break;
				case 'tD': // target Date
					$sort = '&sort=tD';
					break;
				case 'pH': // projected Hours
					$sort = '&sort=pH';
					break;
				case 's':
					$sort = '&sort=s';
					break;
				default:
					$sort = '';
					break;
			}
			$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=getTodos&sID='.$_SESSION['server_sID'].'&lID='.$lId.$limit.$sort.$past), true);
			//echo $GLOBALS['server'].'index.php?action=getTodos&sID='.$_SESSION['server_sID'].'&lID='.$lId.$limit.$sort.$past;
			//print_r($req);
			if(!isset($req['eMsg'])){
				$td = array();
				foreach($req['todos'] as &$todo){
					$td[] = new Todo($todo['id'], 
									$todo['title'],
									$todo['text'],
									$todo['tD'],
									$todo['pH'],
									$this->getUserById($todo['creator']),
									$todo['status']);
				}
				return $td;
			} else return array('Error'=>$req['eMsg']);
		}
		
		/**
		 * 
		 * Saves a new Todo at the Server
		 * @param int $lId
		 * @param string $title
		 * @param string $text
		 * @param string $tD | target Date
		 * @param int $pH | projected Hours
		 * @return int | id of Todo
		 */
		public function newTodo($lId, $title, $text, $tD, $pH){
			$lId = $lId;
			$title = urlencode($title);
			$text = urlencode($text);
			$a = explode('.', ($tD));
			$tD = date('U', mktime(0,0,0,$a[1], $a[0], $a[2]));
			$pH = urlencode($pH);
			
			$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=newTodo&sID='.$_SESSION['server_sID'].'&title='.$title.'&text='.$text.'&tD='.$tD.'&pH='.$pH), true);
			if(isset($req['tID'])){
				$newid = $req['tID'];
				if($newid > -1){
					$req = $this->addTodoToList($lId, $newid);
					if(!isset($req['eMsg'])){
						return $newid;
						break;
					} else return array('Error'=>$req['eMsg']);
				}
			}
			return array('Error'=>$req['eMsg']);
		}
		
		/**
		 * 
		 * Updates a Todo at the Server with the new Params
		 * @param int $id
		 * @param string $title
		 * @param string $text
		 * @param date $tD
		 * @param int $pH
		 * @param string $status
		 */
		public function editTodo($id, $title, $text, $tD, $pH, $status){
			$id = $id;
			$title = urlencode($title);
			$text = urlencode($text);
			$a = explode('.', ($tD));
			$tD = date('U', mktime(0,0,0,$a[1], $a[0], $a[2]));
			$pH = urlencode($pH);

			$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=editTodo&sID='.$_SESSION['server_sID'].'&tID='.$id.'&title='.$title.'&text='.$text.'&tD='.$tD.'&pH='.$pH.'&status='.$status), true);
			if(!isset($req['eMsg'])){
				return $req['tID'];
				break;
			}
			return array('Error'=>$req['eMsg']);
		}
		
		/**
		 * 
		 * Deletes Todo
		 * @param int $id
		 */
		public function deleteTodo($id){
			$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=deleteTodo&sID='.$_SESSION['server_sID'].'&tID='.$id), true);
			if(!isset($req['eMsg'])){
				return true;
				break;
			}
			return array('Error'=>$req['eMsg']);		
		}
		
		/**
		 * 
		 * gets Todo from Server
		 * @param int $tId
		 * @return Todo
		 */
		public function getTodo($tId, $lL=false){
			$l = ($lL) ? '&lL=true' : '';
			$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=getTodo&sID='.$_SESSION['server_sID'].'&tID='.$tId.$l), true);
			//print_r($req);
			if(isset($req['todo'])){
				$td = new Todo($req['todo']['id'], 
								$req['todo']['title'],
								$req['todo']['text'],
								$req['todo']['tD'],
								$req['todo']['pH'],
								$this->getUserById($req['todo']['creator']),
								$req['todo']['status']);
				foreach($req['todo']['users'] as $u){
					$td->addUser(new UserDescription($u['nick'], $u['id'], $u['fN'], $u['lN'], '', ''));
				}
				if($lL){
					foreach($req['todo']['lists'] as $l){
						$td->addProject($l['id'], $l['title']);
					}
				}
				return $td;
				break;
			} 
			return array('Error'=>$req['eMsg']);
		}
		
		/**
		 * 
		 * Get all Project for a specific User or public
		 * @param $limit
		 * @param $sort
		 * @return Project[]
		 */
		public function getProjects($uId=-1, $from=-1, $rows=-1, $sort='', $withoutTodos=false){
			$limit = (($rows == -1) || ($from == -1)) ? '' : '&from='.$from.'&rows='.$rows;
			$sort = ($sort == '') ? '' : 
					(($sort == 'id') ? '&sort=cD' : '&sort=t'); //t...title, cD...changeDate, 
			$pub = ($uId == -1) ? '&pub=true' : '&uID='.$uId;

			$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=getLists&order=asc&sID='.$_SESSION['server_sID'].$limit.$sort.$pub), true);
			//echo$GLOBALS['server'].'index.php?action=getLists&order=asc&sID='.$_SESSION['server_sID'].$limit.$sort.$pub;
			//print_r($req);
			//echo $GLOBALS['server'].'index.php?action=getLists&order=asc&sID='.$_SESSION['server_sID'].$limit.$sort.$pub;
			if(isset($req['lists'])){
				$r = array();
				foreach($req['lists'] as $sreq){
					$staten = $this->getProjectOverview($sreq['id']);
					if(isset($staten['id'])){
						$last_todo_date = isset($staten['lTD']) ? $staten['lTD'] : '';
						$owner = new UserDescription($sreq['owner']['nick'], $sreq['owner']['id'], $sreq['owner']['fN'], $sreq['owner']['lN'], '');
						$p = new Project($sreq['id'], $sreq['title'], $sreq['text'], $sreq['tC'], '', $last_todo_date, $staten['tC'], $staten['tOS'], $staten['tBS'], $staten['tW'], $staten['tN'], $owner);
						$p->setListCount($req['lC']);
						if(!$withoutTodos){
							$t = $this->getTodosForList($p->getId());
							if(!isset($t['Error'])) $p->addTodos($t);
						}
						$r[] = $p;
					} 
				}
				return $r;
				break;
			}
			return array('Error'=>$req['eMsg']);
		}
		
		/**
		 * 
		 * Returns Nubmer of all Projects
		 */
		public function getProjectCount() {
			$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=getLists&order=asc&sID='.$_SESSION['server_sID'].'&from=0&rows=0&sort=t'), true);
			//echo $GLOBALS['server'].'index.php?action=getLists&order=asc&sID='.$_SESSION['server_sID'].'&from=0&rows=0&sort=t';
			if(!isset($req['eMsg'])){
				return $req['lC'];
			} else return array('Error'=>$req['eMsg']);
		}
		
		/**
		 * 
		 * Returns an array of List titles, ids and ownerId
		 * @param unknown_type $from
		 * @param unknown_type $rows
		 * @param unknown_type $order
		 */
		public function getListTitles($from=-1, $rows=-1, $order='') {
			$limit = (($rows == -1) || ($from == -1)) ? '' : '&from='.$from.'&rows='.$rows;
			$order = ($order=='asc') ? '&order=asc' : '&order=desc';
			
			$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=getListTitles&sID='.$_SESSION['server_sID'].$limit.$order), true);

			if(!isset($req['eMsg'])){
				$e = array();
				foreach($req['lists'] as $l){
					$e[] = array('id'=>$l['id'], 'title'=>$l['title'], 'owner'=>$l['oID']);
				}
				return $e;
			} else return array('Error'=>$req['eMsg']);
		}
		
		/**
		 * 
		 * Gets Project Data from the Server
		 * @param integer $id
		 * @return Project
		 */
		public function getProject($id, $fT=false){
			$fT = ($fT) ? '&fT=true' : '';
			
			$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=getList&fT=true&lID='.$id.'&sID='.$_SESSION['server_sID'].$fT), true);
			if(isset($req['list'])){
				$owner = new UserDescription($req['list']['owner']['nick'], $req['list']['owner']['id'], $req['list']['owner']['fN'], $req['list']['owner']['lN'], '');
				$status = (isset($req['list']['public'])) ? Project::STATUS_PUBLIC : Project::STATUS_PRIVATE;
				$p = new Project($req['list']['id'], $req['list']['title'], $req['list']['text'], $req['list']['tC'], '', 
							'', 1, 2, 3, 4, 5, $owner, $status);
				$p->setMsgCount($req['list']['mC']);
				//$p->addTodos($this->getTodosForList($p->getId()));
				if(is_array($req['list']['todos'])){
					foreach($req['list']['todos'] as $todoid){
						$p->addTodo(new Todo($todoid['id'], $todoid['title'], $todoid['text'], $todoid['tD'], $todoid['pH'], $this->getUserById($todoid['creator']), $todoid['status']));
					}
				}
				return $p;
				break;
			}
			return array('Error'=>$req['eMsg']);
		}
		
		/**
		 * 
		 * Sends Project-Data to Server and returns new ID
		 * @param String $title
		 * @param String $text
		 * @param boolean $public 
		 * @return int | id of new Project
		 */
		public function newProject($title, $text, $public=false){
			$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=newList&title='.urlencode($title).'&text='.urlencode($text).'&sID='.$_SESSION['server_sID']), true);
			//print_r($req);
			if(isset($req['lID'])){
				if($public) {
					$r = $this->shareList($req['lID']);
					return ($r===true) ? $req['lID'] : $r;
					break;
				} else {
					return $req['lID'];
					break;
				}
			}
			return array('Error'=>$req['eMsg']);
		}
		
		/**
		 * 
		 * Edits a List at the server
		 * @param int $id
		 * @param string $title
		 * @param string $text
		 * @return int $lID
		 */
		public function editProject($id, $title, $text){
			$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=editList&title='.urlencode($title).'&text='.urlencode($text).'&sID='.$_SESSION['server_sID'].'&lID='.$id), true);
			if(!isset($req['eMsg'])){
				return $req['lID'];
			} else return array('Error'=>$req['eMsg']);
		}
		
		/**
		 * 
		 * Deletes Project
		 * @param unknown_type $id
		 */
		public function deleteProject($id){
			$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=deleteList&sID='.$_SESSION['server_sID'].'&lID='.$id), true);
			if(!isset($req['eMsg'])){
				return $req['lID'];
			} else return array('Error'=>$req['eMsg']);
		}
		
		/**
		 * 
		 * gets Extra Information for Project
		 * @param int $id
		 */
		public function getProjectOverview($id){
			$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=getListOverview&sID='.$_SESSION['server_sID'].'&lID='.$id), true);
			//print_r($req);
			//echo $GLOBALS['server'].'index.php?action=getListOverview&sID='.$_SESSION['server_sID'].'&lID='.$id;
			if(isset($req['lO'])){
        		return $req['lO'];	
        	} else return array('Error'=>$req['eMsg']);
		}
		
		/**
		 * 
		 * Checks if the active Sesion is valid at the Server
		 * Gets called at init.php 
		 */
		public function checkIfValidSession() {
			$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=checkIfValidSession&sID='.$_SESSION['server_sID'].'&uID='.$_SESSION['User']['id']), true);
			if($req['r'] == true){
        		return true;	
        	} else return false;
		}
		
		/**
		 * 
		 * shares List with a User or with everyone (uID=-1)
		 * @param int $lID
		 * @param int $uID
		 */
		public function shareList($lID, $uID=-1){
			$user = ($uID == -1) ? '' : '&uID='.$uID;
			
			$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=shareList&sID='.$_SESSION['server_sID'].'&lID='.$lID.$user), true);
			//echo $GLOBALS['server'].'index.php?action=shareList&sID='.$_SESSION['server_sID'].'&lID='.$lID.$user;
			//print_r($req);
			if(!isset($req['eMsg'])){
				return true;
			} else return array('Error'=>$req['eMsg']);
		}
		
		/**
		 * 
		 * Unshares a List with a user or with every (uID=-1)
		 * @param unknown_type $lID
		 * @param unknown_type $uId
		 */
		public function unshareList($lID, $uID=-1){
			$user = ($uID == -1) ? '' : '&uID='.$uID;
			
			$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=unshareList&sID='.$_SESSION['server_sID'].'&lID='.$lID.$user), true);
			if(!isset($req['eMsg'])){
				return true;
			} else return array('Error'=>$req['eMsg']);			
		}
		
		/**
		 * 
		 * Adds a Todo to a List/Project
		 * @param int $lID
		 * @param int $tID
		 */
		public function addTodoToList($lID, $tID){
			$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=addTodoToList&sID='.$_SESSION['server_sID'].'&lID='.$lID.'&tID='.$tID), true);
			if(!isset($req['eMsg'])){
				return true;
			} else return array('Error'=>$req['eMsg']);
		}
		
		/**
		 * 
		 * Removes a Todo From a List
		 * @param int $lID
		 * @param int $tID
		 */
		public function removeTodoFromList($lID, $tID){
			$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=removeTodoFromList&sID='.$_SESSION['server_sID'].'&lID='.$lID.'&tID='.$tID), true);
			//echo $GLOBALS['server'].'index.php?action=removeTodoFromList&sID='.$_SESSION['server_sID'].'&lID='.$lID.'&tID='.$tID;
			//print_r($req);		
			if(!isset($req['eMsg'])){
				return true;
			} else return array('Error'=>$req['eMsg']);
		}
		
		/**
		 * 
		 * removes a User from a Todo
		 * @param unknown_type $uId
		 * @param unknown_type $tId
		 */
		public function removeUserFromTodo($tID, $uID){
			$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=removeUserFromTodo&sID='.$_SESSION['server_sID'].'&tID='.$tID.'&uID='.$uID), true);
			//echo $GLOBALS['server'].'index.php?action=removeUserFromTodo&sID='.$_SESSION['server_sID'].'&tID='.$tID.'&uID='.$uID;
			//print_r($req);
			if(!isset($req['eMsg'])){
				return true;
			} else return array('Error'=>$req['eMsg']);
		}
		
		/**
		 * 
		 * Sets Users Role in Todo
		 * @param unknown_type $lID
		 * @param unknown_type $uID
		 * @param string $role
		 */
		public function addUserToTodo($tID, $uID, $role){
			$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=setUserTodoRole&sID='.$_SESSION['server_sID'].'&tID='.$tID.'&uID='.$uID.'&role='.$role), true);
			//echo $GLOBALS['server'].'index.php?action=setUserTodoRole&sID='.$_SESSION['server_sID'].'&tID='.$tID.'&uID='.$uID.'&role='.$role;
			//print_r($req);
			if(!isset($req['eMsg'])){
				return true;
			} else return array('Error'=>$req['eMsg']);
		}
		
		/**
		 * 
		 * gets a Message by Id From the Server
		 * @param unknown_type $id
		 * @param unknown_type $fR
		 */
		public function getMessage($id, $fR=false, $order=''){
			$order = ($order=='asc') ? '&rO=asc' : '&rO=desc';
			$fR = ($fR) ? '&fR=true' : '';
			$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=getMsg&sID='.$_SESSION['server_sID'].'&mID='.$id.$fR.$order), true);
			
			if(!isset($req['eMsg'])){
				$lID = isset($req['msg']['lID']) ? $req['msg']['lID'] : -1;
				$uID = isset($req['msg']['uID']) ? $req['msg']['uID'] : -1;
				$tID = isset($req['msg']['tID']) ? $req['msg']['tID'] : -1;
				$mID = isset($req['msg']['mID']) ? $req['msg']['mID'] : -1;
				$rep = isset($req['msg']['r']) ? $req['msg']['r'] : array();
				$author = new UserDescription($req['msg']['author']['nick'], $req['msg']['author']['id'], $req['msg']['author']['fN'], $req['msg']['author']['lN'], '', 0);
				return new Message($req['msg']['id'], $author, $req['msg']['title'],  $req['msg']['text'],  $req['msg']['date'], $rep, $lID, $mID, $uID, $tID);;
			} else return array('Error'=>$req['eMsg']);
		}
		
		/**
		 * 
		 * Gets Messages from Server
		 * @param unknown_type $from
		 * @param unknown_type $rows
		 * @param unknown_type $order
		 * @param unknown_type $uID
		 * @param unknown_type $lID
		 * @param unknown_type $mID
		 * @param unknown_type $tID
		 * @param unknown_type $fR
		 */
		public function getMessages($from=-1, $rows=-1, $order='', $uID=-1, $lID=-1, $mID=-1, $tID=-1, $fR=false){
			$order = ($order=='asc') ? '&order=asc' : '&order=desc';
			$limit = (($rows == -1) || ($from == -1)) ? '' : '&from='.$from.'&rows='.$rows;
			$id = ($uID != -1) ? '&lUID='.$uID :
						(($lID != -1) ? '&lLID='.$lID :
						(($mID != -1) ? '&lMID='.$mID : 
						(($tID != -1) ? '&lTID='.$tID : '')));
			$fR = ($fR) ? '&fR=true' : '';
			if($id != '') {
				$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=getMsgs&sID='.$_SESSION['server_sID'].$id.$limit.$order.$fR), true);
				
				if(!isset($req['eMsg'])){
					$r = array();
					if(isset($req['msgs'])){
						foreach($req['msgs'] as $msg){
							$lID = isset($msg['lID']) ? $msg['lID'] : -1;
							$uID = isset($msg['uID']) ? $msg['uID'] : -1;
							$tID = isset($msg['tID']) ? $msg['tID'] : -1;
							$mID = isset($msg['mID']) ? $msg['mID'] : -1;
							$rep = isset($msg['r']) ? $msg['r'] : array();
							//TODO: limit mit replys
							$author = new UserDescription($msg['author']['nick'], $msg['author']['id'], $msg['author']['fN'], $msg['author']['lN'], '', 0);
							$u = new Message($msg['id'], $author, $msg['title'],  $msg['text'],  $msg['date'], $rep, $lID, $mID, $uID, $tID);
							$u->setAllMsgCount($req['mC']);
							$r[] = $u;
						}
					}
					return $r;
				} else return array('Error'=>$req['eMsg']);
			} else return false;
		}
		
		/**
		 * 
		 * Gets Messages for a Todo -> return $this->getMsgs
		 * @param unknown_type $id
		 * @param unknown_type $from
		 * @param unknown_type $rows
		 * @param unknown_type $order
		 * @param unknown_type $fR
		 */
		public function getMessagesForTodo($id, $from=-1, $rows=-1, $order='', $fR=false){
			return $this->getMessages($from, $rows, $order, -1, -1, -1, $id, $fR);
		}
		
		/**
		 * 
		 * Gets Messages for a List -> return $this->getMsgs
		 * @param unknown_type $id
		 * @param unknown_type $from
		 * @param unknown_type $rows
		 * @param unknown_type $order
		 * @param unknown_type $fR
		 */
		public function getMessagesForList($id, $from=-1, $rows=-1, $order='', $fR=false){
			return $this->getMessages($from, $rows, $order, -1, $id, -1, -1, $fR);
		}
		
		/**
		 * 
		 * Gets Messages for a User -> return $this->getMsgs
		 * @param unknown_type $id
		 * @param unknown_type $from
		 * @param unknown_type $rows
		 * @param unknown_type $order
		 * @param unknown_type $fR
		 */
		public function getMessagesForUser($id, $from=-1, $rows=-1, $order='', $fR=false){
			return $this->getMessages($from, $rows, $order, $id, -1, -1, -1, $fR);
		}
		
		/**
		 * 
		 * Gets Messages for a Message -> return $this->getMsgs
		 * @param unknown_type $id
		 * @param unknown_type $from
		 * @param unknown_type $rows
		 * @param unknown_type $order
		 * @param unknown_type $fR
		 */
		public function getMessagesForMessage($id, $from=-1, $rows=-1, $order='', $fR=false){
			return $this->getMessages($from, $rows, $order, -1, -1, $id, -1, $fR);
		}
		
		/**
		 * 
		 * Creates a new Message at Server
		 * @param unknown_type $title
		 * @param unknown_type $text
		 * @param unknown_type $mID
		 * @param unknown_type $tID
		 * @param unknown_type $uID
		 * @param unknown_type $lID
		 */
		public function newMessage($title, $text, $mID=-1, $tID=-1, $uID=-1, $lID=-1){
			$id = ($uID != -1) ? '&lUID='.$uID :
						(($lID != -1) ? '&lLID='.$lID :
						(($mID != -1) ? '&lMID='.$mID : 
						(($tID != -1) ? '&lTID='.$tID : '')));
			
			$req = json_decode($this->getJSON($GLOBALS['server'].'index.php?action=newMsg&sID='.$_SESSION['server_sID'].$id.'&title='.urlencode($title).'&text='.urlencode($text)), true);
		
			if(!isset($req['eMsg'])){
				return true;
			} else return array('Error'=>$req['eMsg']);
		}
		
		/**
		 * 
		 * Helper function for HTTP Request
		 * @param String $link
		 * @return string
		 */
		private function getJSON($link){
			$s = microtime(true);
			$handle = fopen($link, 'r');
			if($handle){
				$req = stream_get_contents($handle);
				fclose($handle);
				$e = microtime(true);
				$GLOBALS['db_connections']++;
				$GLOBALS['waited_time']+=$e-$s;
				unset($s);
				unset($e);
				return $req;
			}
			unset($s);
			return '';
		}
	}
?>